package org.eclipse.moquette.parser.netty;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import org.eclipse.moquette.proto.messages.AbstractMessage;
import org.eclipse.moquette.proto.messages.PublishMessage;

/**
 * Publish message 编码
 * Created by alex on 15-5-25.
 */
public class PublishEncoder extends DemuxEncoder<PublishMessage> {

    @Override
    protected void encode(ChannelHandlerContext ctx, PublishMessage message, ByteBuf out) {

        //qos 不可以是0
        if (message.getQos() == AbstractMessage.QOSType.RESERVED) {
            throw new IllegalArgumentException("Found a message with RESERVED Qos");
        }

        if (message.getTopicName() == null || message.getTopicName().isEmpty()) {
            throw new IllegalArgumentException("Found a message with empty or null topic name");
        }

        ByteBuf variableHeaderBuff = ctx.alloc().buffer(2);
        ByteBuf buff = null;

        try {
            //先写topicName
            variableHeaderBuff.writeBytes(Utils.encodeString(message.getTopicName()));
            //qos 1 or 2 必须给MessageID
            if (message.getQos() == AbstractMessage.QOSType.LEAST_ONE ||
                    message.getQos() == AbstractMessage.QOSType.EXACTLY_ONCE) {
                if (message.getMessageID() == null) {
                    throw new IllegalArgumentException("Found a message with Qos 1 or Qos 2 , but have not messageId");
                }
                variableHeaderBuff.writeShort(message.getMessageID());
            }
            //写入payload
            variableHeaderBuff.writeBytes(message.getPayload());

            int variableHeaderSize = variableHeaderBuff.readableBytes();

            byte flags = Utils.encodeFlags(message);

            buff = ctx.alloc().buffer(2 + variableHeaderSize);
            buff.writeByte(AbstractMessage.PUBLISH << 4 | flags);
            buff.writeBytes(Utils.encodeRemainingLength(variableHeaderSize));
            buff.writeBytes(variableHeaderBuff);
            out.writeBytes(buff);

        }finally {
            variableHeaderBuff.release();
            if (buff != null){
                buff.release();
            }
        }
    }
}
